package com.mlink.ai.chat.ui.fragment

import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.FragmentExploreAllCategoryBinding
import com.mlink.ai.chat.bean.ExploreCategory
import com.mlink.ai.chat.bean.ExploreSubCategory
import com.mlink.ai.chat.constants.KEY_CHAT_PROMPT
import com.mlink.ai.chat.ui.activity.ChatActivity
import com.mlink.ai.chat.ui.activity.PromptCreateActivity
import com.mlink.ai.chat.ui.adapter.ExploreAllAdapter
import com.mlink.ai.chat.ui.viewmodel.ExploreViewModel
import com.mlink.ai.chat.utils.AnalyticsEvents
import com.mlink.ai.chat.utils.AnalyticsParams
import com.mlink.ai.chat.utils.PromptUtils
import com.mlink.ai.chat.utils.logEvent

class ExploreAllCategoryFragment : BaseFragment<FragmentExploreAllCategoryBinding>() {

    private var listener: OnSeeAllListener? = null

    private var subCategoryLoggedList = mutableListOf<String>() // 已经打过的点，存储 (ExploreCategory id)_(ExploreSubCategory id)

    companion object {
        fun newInstance() = ExploreAllCategoryFragment()
    }

    private val viewModel: ExploreViewModel by lazy {
        ViewModelProvider(requireActivity())[ExploreViewModel::class.java]
    }

    override fun getViewBinding(): FragmentExploreAllCategoryBinding {
        return FragmentExploreAllCategoryBinding.inflate(layoutInflater)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.categoriesLiveDada.observe(this.viewLifecycleOwner) {
            showAllCategory(it)
        }
        binding.createIv.setOnClickListener {
            startActivity(Intent(requireContext(), PromptCreateActivity::class.java).apply {
                putExtra(PromptCreateActivity.EXTRA_CATEGORY_ID, 1)
            })
            AnalyticsEvents.AC_EXP_PPT_CREATE_CLICK.logEvent(Bundle().apply {
                putString(AnalyticsParams.CATEGORY, "floating_button")
            })
        }

        logCreateCategoryFloatButtonShowEvent()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            logCreateCategoryFloatButtonShowEvent()
            computeItemVisibleArea(binding.recyclerView)
        } else {
            subCategoryLoggedList.clear()
        }
    }

    private fun logCreateCategoryFloatButtonShowEvent() {
        AnalyticsEvents.AC_EXP_PPT_CREATE_SHOW.logEvent(Bundle().apply {
            putString(AnalyticsParams.CATEGORY, "floating_button")
        })
    }

    private fun showAllCategory(categories: List<ExploreCategory>) {
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            adapter = ExploreAllAdapter().apply {
                setOnItemOperateListener(object : ExploreAllAdapter.OnItemOperateListener {
                    override fun onSeeAll(position: Int, category: ExploreCategory) {
                        listener?.onSeeAll(position, category)
                    }

                    override fun onCreateItemClicked(category: ExploreCategory) {
                        startActivity(Intent(requireContext(), PromptCreateActivity::class.java).apply {
                            putExtra(PromptCreateActivity.EXTRA_CATEGORY_ID, category.id)
                        })
                        AnalyticsEvents.AC_EXP_PPT_CREATE_CLICK.logEvent(Bundle().apply {
                            putString(AnalyticsParams.CATEGORY, category.categoryEventName)
                        })
                    }

                    override fun deleteItem(position: Int, subCategory: ExploreSubCategory) {
                        context?.let {
                            viewModel.getAllCategory(it)
                        }
                    }

                    override fun onSubCategoryItemClicked(mainCategory: ExploreCategory, subCategory: ExploreSubCategory) {
                        startActivity(Intent(requireContext(), ChatActivity::class.java).apply {
                            putExtra(KEY_CHAT_PROMPT, subCategory.prompt)
                        })

                        AnalyticsEvents.AC_EXP_PPT_CLICK.logEvent(Bundle().apply {

                            val type = if (subCategory.isCustom) "custom" else "preset"
                            putString(AnalyticsParams.CATEGORY, mainCategory.categoryEventName)
                            putString(AnalyticsParams.KEY_TITLE, subCategory.categoryEventName)
                            putString(AnalyticsParams.KEY_TYPE, type)
                        })
                    }

                    override fun onDeleteShow(view: View) {
                        val fragment = parentFragment as? ExploreFragment
                        fragment?.let {
                            it.deleteView?.isVisible = false
                            it.deleteView = view
                        }
                    }
                })
                setData(categories)
            }.also {
                it.notifyDataSetChanged()
            }

            addOnScrollListener(object : OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    computeItemVisibleArea(recyclerView)
                }
            })

            post {
                computeItemVisibleArea(this)
            }
        }
    }

    override fun onDestroyView() {
        val fragment = parentFragment as? ExploreFragment
        fragment?.deleteView = null
        super.onDestroyView()
    }

    private fun computeItemVisibleArea(recyclerView: RecyclerView) {
        val verticalLayoutManager = recyclerView.layoutManager as LinearLayoutManager
        for (i in 0 until verticalLayoutManager.childCount) {
            val child = verticalLayoutManager.getChildAt(i)
            if (child != null) {
                val verticalAdapterPosition = verticalLayoutManager.getPosition(child)
                val horizontalRecyclerView = child.findViewById<RecyclerView>(R.id.recycler_view)
                val category = (recyclerView.adapter as ExploreAllAdapter).getData()[verticalAdapterPosition]
                computeHorizontalItemArea(category, horizontalRecyclerView, verticalAdapterPosition)

                horizontalRecyclerView.addOnScrollListener(object : OnScrollListener() {
                    override fun onScrollStateChanged(
                        recyclerView: RecyclerView,
                        newState: Int
                    ) {
                        super.onScrollStateChanged(recyclerView, newState)

                        computeHorizontalItemArea(category, recyclerView, verticalAdapterPosition)
                    }
                })
            }
        }
    }

    private fun computeHorizontalItemArea(category: ExploreCategory,
        recyclerView: RecyclerView,
        verticalAdapterPosition: Int
    ) {
        val layoutManager = recyclerView.layoutManager as LinearLayoutManager
        val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
        val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

        for (i in firstVisibleItemPosition..lastVisibleItemPosition) {
            val childView = layoutManager.getChildAt(i - firstVisibleItemPosition)
            if (childView != null && childView.width != 0 && childView.height != 0) {
                val horizontalAdapterPosition = layoutManager.getPosition(childView)
                val visibleArea = childView.width * childView.height
                val totalArea = childView.measuredWidth * childView.measuredHeight
                if (visibleArea * 1.0f / totalArea >= 2.0f / 3) {
                    // 该 item 显示了自身面积的 2/3 及以上
                    if (horizontalAdapterPosition in category.subCategories.indices) {
                        val subCategory = category.subCategories[horizontalAdapterPosition]
                        val markId = category.id.toString() + "_" + subCategory.id
                        if (!subCategoryLoggedList.contains(markId)) {
                            if (subCategory.id != PromptUtils.PROMPT_CREATE_ITEM_ID) {
                                AnalyticsEvents.AC_EXP_PPT_SHOW.logEvent(Bundle().apply {
                                    putString(AnalyticsParams.CATEGORY, category.categoryEventName)
                                    putString(AnalyticsParams.KEY_TITLE, subCategory.categoryEventName)
                                    val type = if (subCategory.isCustom) "custom" else "preset"
                                    putString(AnalyticsParams.KEY_TYPE, type)
                                })
                            } else {
                                AnalyticsEvents.AC_EXP_PPT_CREATE_SHOW.logEvent(Bundle().apply {
                                    putString(AnalyticsParams.CATEGORY, category.categoryEventName)
                                })
                            }
                            subCategoryLoggedList.add(markId)
                        }
                    }
                }
            }
        }
    }

    fun setOnSeeAllListener(listener: OnSeeAllListener) {
        this.listener = listener
    }

    interface OnSeeAllListener {
        fun onSeeAll(position: Int, category: ExploreCategory)
    }
}